package co.recloud.ariadne.store;

import co.recloud.ariadne.model.Address;
import co.recloud.ariadne.model.Host;
import co.recloud.ariadne.model.logical.Transaction;

public class AddressTable {
	private static AddressTable singleton;
	private static final String AT_SCHEMA = "address_table";
	private static final String AT_CF = "at";
	private static final String AT_COLUMN = "host_id";
	public synchronized static AddressTable getInstance() {
		if(singleton == null) {
			singleton = new AddressTable();
		}
		return singleton;
	}
	public Host resolve(Transaction transaction, String schema, String columnFamily, String key) {
		Host host = null;
		String path = schema + "." + columnFamily + ":" + key;
		Long hash = new Long(path.hashCode());
		HostTable ht = HostTable.getInstance();
		if(schema.equals(AT_SCHEMA)) {
			host = ht.findByHash(hash);
		} else {
			TransactionCache cache = TransactionCache.getInstance();
			String tokenStr = cache.getString(transaction, AT_SCHEMA, AT_CF, path, AT_COLUMN, false);
			if(tokenStr != null) {
				host = ht.findByHash(Long.parseLong(tokenStr));
			} else {
				host = ht.findByHash(new Long(path.hashCode()));
				cache.putColumn(transaction, AT_SCHEMA, AT_CF, path, AT_COLUMN, host.getToken().toString());
			}
		}
		return host;
	}
	public Address getCoReplica(Address primaryAddress) {
		// TODO Auto-generated method stub
		return null;
	}
	public boolean isReplica(Address target) {
		// TODO Auto-generated method stub
		return false;
	}
	public void setHost(Transaction transaction, String path, Host target) {
		TransactionCache cache = TransactionCache.getInstance();
		cache.putColumn(transaction, AT_SCHEMA, AT_CF, path, AT_COLUMN, target.getToken().toString());
	}
}
